import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';

class CalendarBottomSheet extends StatefulWidget {
  final DateTime selectedDate;
  final Function(DateTime) onDateSelected;

  const CalendarBottomSheet({
    super.key,
    required this.selectedDate,
    required this.onDateSelected,
  });

  @override
  State<CalendarBottomSheet> createState() => _CalendarBottomSheetState();
}

class _CalendarBottomSheetState extends State<CalendarBottomSheet> {
  late DateTime _currentMonth;
  late DateTime _selectedDate;

  @override
  void initState() {
    super.initState();
    _currentMonth = DateTime(
      widget.selectedDate.year,
      widget.selectedDate.month,
    );
    _selectedDate = widget.selectedDate;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: 441.h,
      decoration: ShapeDecoration(
        color: Colors.black,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(30.r),
            topRight: Radius.circular(30.r),
          ),
        ),
      ),
      child: Column(
        children: [
          _buildHeader(),
          _buildWeekDays(),
          Expanded(child: _buildCalendarGrid()),
        ],
      ),
    );
  }

  Widget _buildHeader() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          GestureDetector(
            onTap: _previousMonth,
            child: Icon(Icons.chevron_left, color: Colors.white, size: 24.sp),
          ),
          Text(
            _getMonthYearString(_currentMonth),
            style: TextStyle(
              color: Colors.white,
              fontSize: 16.sp,
              fontFamily: 'Pangram',
              fontWeight: FontWeight.w500,
            ),
          ),
          GestureDetector(
            onTap: _nextMonth,
            child: Icon(Icons.chevron_right, color: Colors.white, size: 24.sp),
          ),
        ],
      ),
    );
  }

  Widget _buildWeekDays() {
    const weekDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: weekDays.map((day) {
          return Expanded(
            child: Text(
              day,
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.white70,
                fontSize: 12.sp,
                fontFamily: 'Pangram',
                fontWeight: FontWeight.w400,
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildCalendarGrid() {
    final daysInMonth = _getDaysInMonth(_currentMonth);
    final firstDayOfMonth = DateTime(
      _currentMonth.year,
      _currentMonth.month,
      1,
    );
    final startingWeekday =
        firstDayOfMonth.weekday % 7; // 0 = Sunday, 1 = Monday, etc.

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 7,
          childAspectRatio: 1,
          mainAxisSpacing: 8.h,
          crossAxisSpacing: 0,
        ),
        itemCount: 42, // 6 weeks * 7 days
        itemBuilder: (context, index) {
          final dayIndex = index - startingWeekday;

          if (dayIndex < 0 || dayIndex >= daysInMonth) {
            // Previous month or next month days
            DateTime displayDate;
            int displayDay;

            if (dayIndex < 0) {
              // Previous month
              final prevMonth = DateTime(
                _currentMonth.year,
                _currentMonth.month - 1,
              );
              final prevMonthDays = _getDaysInMonth(prevMonth);
              displayDay = prevMonthDays + dayIndex + 1;
              displayDate = DateTime(
                prevMonth.year,
                prevMonth.month,
                displayDay,
              );
            } else {
              // Next month
              displayDay = dayIndex - daysInMonth + 1;
              final nextMonth = DateTime(
                _currentMonth.year,
                _currentMonth.month + 1,
              );
              displayDate = DateTime(
                nextMonth.year,
                nextMonth.month,
                displayDay,
              );
            }

            return _buildDayItem(
              displayDay,
              displayDate,
              isCurrentMonth: false,
            );
          } else {
            // Current month days
            final day = dayIndex + 1;
            final date = DateTime(_currentMonth.year, _currentMonth.month, day);
            return _buildDayItem(day, date, isCurrentMonth: true);
          }
        },
      ),
    );
  }

  Widget _buildDayItem(int day, DateTime date, {required bool isCurrentMonth}) {
    final isSelected = _isSameDay(date, _selectedDate);
    final isToday = _isSameDay(date, DateTime.now());
    final today = DateTime.now();
    final isSelectableDate = date.isBefore(today) || _isSameDay(date, today);

    return GestureDetector(
      onTap: isSelectableDate
          ? () {
              setState(() {
                _selectedDate = date;
              });
              widget.onDateSelected(date);
              Navigator.of(context).pop();
            }
          : null,
      child: Container(
        margin: EdgeInsets.all(2.w),
        decoration: BoxDecoration(
          color: isSelected
              ? const Color(0xFFFF8C00)
              : isToday
              ? Colors.white24
              : Colors.transparent,
          shape: BoxShape.circle,
        ),
        child: Center(
          child: Text(
            day.toString(),
            style: TextStyle(
              color: isCurrentMonth
                  ? (isSelected
                        ? Colors.white
                        : isSelectableDate
                        ? Colors.white
                        : Colors.white38)
                  : Colors.white38,
              fontSize: 16.sp,
              fontFamily: 'Pangram',
              fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
            ),
          ),
        ),
      ),
    );
  }

  void _previousMonth() {
    setState(() {
      _currentMonth = DateTime(_currentMonth.year, _currentMonth.month - 1);
    });
  }

  void _nextMonth() {
    setState(() {
      _currentMonth = DateTime(_currentMonth.year, _currentMonth.month + 1);
    });
  }

  int _getDaysInMonth(DateTime date) {
    return DateTime(date.year, date.month + 1, 0).day;
  }

  bool _isSameDay(DateTime date1, DateTime date2) {
    return date1.year == date2.year &&
        date1.month == date2.month &&
        date1.day == date2.day;
  }

  String _getMonthYearString(DateTime date) {
    return '${date.year}-${date.month}-${date.day}';
  }
}
